/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import android.app.LocalActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.TopBar;
import com.mol.market.common.util.Utils;

/**
 * 首页，Tab分页
 * @author Chaos	
 * @since 0.9.6
 * @date 2012-10-12
 */
public class HomeActivityTab extends SherlockFragmentActivity {

    private Session mSession = null;
    
    private LocalActivityManager mLm = null;
    
    /**
     * Tab分栏中的“New”动画
     */
    private AnimationDrawable mAnimation = null;
    
    private BroadcastReceiver mThemeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TopBar.initSkin(mSession, HomeActivityTab.this);
            initSkin();
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home_activity_tab);
        
        mSession = Session.get(this);

        IntentFilter themeFilter = new IntentFilter(Constants.BROADCAST_CHANGE_THEME);
        registerReceiver(mThemeReceiver, themeFilter);
        //是否播放动画 
        boolean isShowAnimation = mSession.getIsShowHighQualityTabAnimation();
        
        initTopBar();
        
        initAnimtion(isShowAnimation);
        
        initTab(savedInstanceState,isShowAnimation);
        
        if(isShowAnimation){
            startAnimation(mAnimation,true);
        }
    }
    
    private void initTopBar() {

        TopBar.createTopBar(
                mSession,
                this, 
                new View[] { 
                    findViewById(R.id.logo), 
                    findViewById(R.id.top_bar_search),
//                    findViewById(R.id.top_bar_rebate)
                },
                new int[] { 
                    View.VISIBLE, 
                    View.VISIBLE,
//                    isShowRebate
                },
                "");
    }
    
    /**
     * 初始化动画
     * @param isShowAnimation
     */
    private void initAnimtion(boolean isShowAnimation){
        if(isShowAnimation){
            mAnimation = (AnimationDrawable) getResources().getDrawable(R.drawable.new_animation);
        }
    }
    
    private void initTab(Bundle savedInstanceState,boolean isShowAnimation){
        TabHost mTabHost = (TabHost) findViewById(android.R.id.tabhost); 
        
        mLm = new LocalActivityManager(getParent(), false);
        mLm.dispatchCreate(savedInstanceState);
        
        mTabHost.setup(mLm);
        
        mTabHost.getTabWidget().setPadding(
                mSession.mTabMargin72 - getTabAugment(isShowAnimation), 
                0, 
                mSession.mTabMargin72 - getTabAugment(isShowAnimation), 
                0);
        FrameLayout fl = (FrameLayout) mTabHost.findViewById(R.id.tab_frame_layout);
        fl.setBackgroundResource(ThemeManager.getResource(mSession, ThemeManager.KEY_TAB_BG));
        
        Intent homeIntent = new Intent(getApplicationContext(), HomeActivity.class);
        TabSpec tab1 = mTabHost
                .newTabSpec(Constants.CATEGORY_HOME)
                .setIndicator(
                        Utils.createTabView(getApplicationContext(), mSession, 
                                getString(R.string.label_recommend), -1, null
                                ))
                                .setContent(homeIntent);
        mTabHost.addTab(tab1);
        
        TabSpec tab2 = mTabHost
                .newTabSpec(Constants.CATEGORY_STAR)
                .setIndicator(getTabAccordingAnimationFlags(isShowAnimation))
                .setContent(R.id.tab_fragment);
        mTabHost.addTab(tab2);
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
          @Override
          public void onTabChanged(String tabId) {
             if (Constants.CATEGORY_STAR.equals(tabId)) {
                 
                 if(mSession.getIsShowHighQualityTabAnimation()){
                     stopAnimation(mAnimation,false);
                     mSession.setIsShowHighQualityTabAnimtion(false);
                 }
                 
               Utils.trackEvent(HomeActivityTab.this, Constants.GROUP_2,
                   Constants.CLICK_STAR);
             }
          }
        });
    }

    @Override
    protected void onDestroy() {
        if(mLm == null){
            mLm = new LocalActivityManager(getParent(), false);
        }
        mLm.dispatchDestroy(false);
        super.onDestroy();
        unregisterReceiver(mThemeReceiver);
    }

    @Override
    protected void onPause() {
        if(mLm == null){
            mLm = new LocalActivityManager(getParent(), false);
        }
        mLm.dispatchPause(false);
        super.onPause();
    }

    @Override
    protected void onResume() {
        if(mLm == null){
            mLm = new LocalActivityManager(getParent(), false);
        }
        mLm.dispatchResume();
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        if(mLm == null){
            mLm = new LocalActivityManager(getParent(), false);
        }
        mLm.dispatchStop();
        super.onStop();
    }
    
    private void initSkin(){
        View tabBg = findViewById(R.id.tab_frame_layout);
        tabBg.setBackgroundResource(ThemeManager.getResource(mSession, ThemeManager.KEY_TAB_BG));
        
        Utils.tabInitSkin(this, mSession);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return getParent().onKeyDown(keyCode, event);
    }
    
    /**
     * 得到Tab的扩充量
     * @param isShowAnimation 如果过false,return 0.
     * @return
     */
    private int getTabAugment(boolean isShowAnimation){
        return isShowAnimation?(int) (mSession.density * 14):0;
    }
    
    /**
     * 根据是否显示动画创建Tab
     * @param isShowAnimation
     * @return
     */
    private View getTabAccordingAnimationFlags(boolean isShowAnimation){
        //don't use 3'yuan expression
        if(isShowAnimation){
            return Utils.createTabWithAnimation(
                    getApplicationContext(), 
                    mSession, 
                    getString(R.string.highquality), 
                    1,
                    mAnimation);
        }else{
            return Utils.createTabView(
                    getApplicationContext(), 
                    mSession, 
                    getString(R.string.highquality), 
                    1, 
                    null);
        }
    }
    
    /**
     * 开始动画
     * @param animation 要开始的动画实例。
     * @param repeat    动画是否重复播放,直到调用{@link #stopAnimation(AnimationDrawable, boolean)}
     */
    private void startAnimation(final AnimationDrawable animation,boolean repeat){
        if(animation == null || animation.isRunning()){
            //meaningless
            return ;
        }
        if(repeat){
            animation.setOneShot(false);
        }
        //It is not running, if it is at the start of the program
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            
            @Override
            public void run() {
                animation.start();
            }
        }, 100);
    }
    
    /**
     * 停止/取消动画 
     * @param animation 要停止的动画实例。
     * @param visble    动画停止之后是否显示。
     */
    private void stopAnimation(final AnimationDrawable animation,boolean visble){
        if(animation == null || !animation.isRunning()){
            //meaningless
            return ;
        }
        
        animation.stop();
        
        if(!visble){
            TabHost mTabHost = (TabHost) findViewById(android.R.id.tabhost);
            View anim = mTabHost.findViewById(R.id.iv_animation);
            anim.setBackgroundDrawable(null);
            anim.setVisibility(View.GONE);
        }
    }
}
